/**
 * Created by nitin on 3/24/14.
 */
function TableCtrl($scope, $fileUploader, $http, $filter) {
    $scope.tableView = 9;
    $scope.tableCurrent = 0;
    $scope.tableSelect = "before";
    $scope.tableSelectDetailDisplay = false;
    //$filter('date')("2014-04-02 20:00:00", "short");
    $scope.tableDetailCancel = function (callback) {
        $scope.tableFileWaiting = false;
        $scope.tableSelectDetailDisplay = false;
        if (callback instanceof Function)
            callback();
        $scope.search();
    };
    $scope.tableDataFilter = function (row, cellName) {
        var value = row[cellName];
        switch (cellName) {
            case "created":
                return $filter('date')(value, 'dd/MM/yyyy');
                break;
            case "price":
                return $filter('number')(value, 0) + '$';
                break;
            default:
                return row[cellName];
        }
    };
    $scope.tableClassFilter = function (row, cellName) {
        var value = row[cellName];
        switch (cellName) {
            case "status":
                return value == "1" ? "active" : "non";
                break;
            default:
                return "";
        }
    };
    $scope.tableRowDeleted = function () {
        var itemSelect = $scope.tableList[this.$index];
        var rowIndex = this.$index;

        var deleteItem = function () {
            var data = {api: 2222, id: itemSelect.id};
            $http.post(BACK_END_BOM + 'delete.php?format=json', data)
                .success(function (data, status, headers, config) {
                    $scope.tableUploader.clearQueue();
                    console.info("delete success ", data);
                    if (data.success)
                        $scope.tableList.splice(rowIndex, 1);
                }).error(function (data, status, headers, config) {
                    console.info("delete  error ", data)
                });
        }
        $scope.messageCreate({
            title: "Delete item " + itemSelect.name, text: "This function will delete permantly",
            type: 2,//YES-NO dialog
            yes: function () {
                deleteItem();
            },
            no: function () {
            }
        });
    };
    $scope.tableRowSelected = function () {
        $scope.tableItemSelect = $scope.tableList[this.$index];

        $http.get(BACK_END_BACK + 'photo.php?format=json', {
            params: { id: $scope.tableItemSelect.id, type: 'avt' }})
            .success(function (data, status, headers, config) {
                $scope.tableUploader.clearQueue();
                if (!data.nodata) {
                    $scope.tableUploader.addSourceToQueue(data[0].file);
                }
                $scope.tableSelectDetailDisplay = true;
            }).error(function (data, status, headers, config) {
                console.info("photo  error ", data)
            });
    };
    $scope.tableRowInsert = function () {
        var newItem = new Object();
        angular.forEach($scope.tableHeadList, function (value) {
            this[value.text] = null;
        }, newItem);
        $scope.tableItemSelect = newItem;
        $scope.tableUploader.clearQueue();
        $scope.tableSelectDetailDisplay = true;
    };
    //$scope.fileUploadId;
    $scope.tableCommitUpload = function () {
        var data = $scope.tableItemSelect;

        if (!data.id) {
            data.api = 1222;
            $http.post(BACK_END_BOM + 'insert.php?format=json', data)
                .success(function (data, status, headers, config) {
                    console.info("Insert success data ", data);
                    if (data.success == true) {
                        $scope.fileUploadId = data.id;
                        $scope.tableItemSelect.id = data.id;
                        $scope.tableList.push($scope.tableItemSelect);

                        if ($scope.tableUploader.getNotUploadedItems().length) {
                            $scope.tableUploader.queue[0].formData = [
                                {id: $scope.tableItemSelect.id, type: "avt"}
                            ];
                            $scope.tableFileWaiting = true;
                            $scope.tableUploader.uploadAll();
                        } else {
                            $scope.tableDetailCancel();
                        }
                    }
                }).error(function (data, status, headers, config) {
                    console.info("data error ", data)
                });
            return;
        }
        data.api = 3222;
        $http.post(BACK_END_BOM + 'update.php?format=json', data)
            .success(function (data, status, headers, config) {
                console.info("Update success data ", data);
                //$scope.fileUploadId = data.id;
                if ($scope.tableUploader.getNotUploadedItems().length) {
                    $scope.tableUploader.queue[0].formData = [
                        {id: $scope.tableItemSelect.id, type: "avt"}
                    ];
                    $scope.tableFileWaiting = true;
                    $scope.tableUploader.uploadAll();
                } else {
                    $scope.tableDetailCancel();
                }
            }).error(function (data, status, headers, config) {
                console.info("data error ", data)
            });
    };
    $scope.tableClearAvt = function () {
        if (!$scope.tableUploader.queue[0].file.src) {
            $scope.tableUploader.clearQueue();
            return;
        }
        var removeImg = function () {
            var data = {api: 2230, id: $scope.tableItemSelect.id, type: "avt"};
            $scope.tableFileWaiting = true;
            $http.post(BACK_END_BOM + 'photo.php?format=json', data)
                .success(function (data, status, headers, config) {
                    console.info("Delete photo success!", data);
                    $scope.tableFileWaiting = false;
                    if (data.success)
                        $scope.tableUploader.clearQueue();
                }).error(function (data, status, headers, config) {
                    console.info("Delete photo error! ", data)
                });
        }
        $scope.messageCreate({
            title: "Please be carefull to delete", text: "This function will delete permantly",
            type: 2,//YES-NO dialog
            yes: function () {
                removeImg();
            },
            no: function () {
            }
        });
    };

    var uploader = $scope.tableUploader = $fileUploader.create({
        scope: $scope,
        // to automatically update the html. Default: $rootScope
        url: BACK_END_BOM + 'upload.php?format=json',
        queueLimit: 1
    });

    uploader.bind('completeall', function (event, items) {
        $scope.tableDetailCancel();
    });
    uploader.bind('success', function (event, xhr, item, response) {
        console.info('Upload success', xhr, item, response);
    });
    var productList = [];
    $http.get(BACK_END_URL + 'index.php?format=json').success(function (data) {
        productList = data.posts;
        if (data.posts.length)
            $scope.tableHeadList = getKeys(data.posts[0]);
        $scope.tableList = productList;
        $scope.search();

    });
    var getKeys = function (obj) {
        var keys = [];
        for (var key in obj)
            keys.push({text: key});
        return keys;
    }

//    $scope.tablePages = function (index) {
//        var page = [];
//        var tag = [];
//        var pageNo = Math.ceil(productList.length / $scope.tableView);
//        for (var i = 0; i < pageNo; i++) {
//            page.push(new Object(productList.slice(i * $scope.tableView, (i + 1) * $scope.tableView)));
//            tag[i] = i;
//        }
//        if (index != undefined)
//            return page[index];
//        else return tag;
//    }
//    $scope.productSelected = function () {
//        $scope.gridItemSelect = $scope.productPages($scope.gridCurrent)[this.$index];
//        $scope.gridSelectDetailDisplay = true;
//    }
    $scope.sort = {
        sortingOrder: 'id',
        reverse: false
    };

    $scope.gap = 5;

    $scope.filteredItems = [];
    $scope.groupedItems = [];
    $scope.itemsPerPage = 3;
    $scope.pagedItems = [];
    $scope.currentPage = 0;
    var searchMatch = function (haystack, needle) {
        if (!needle) {
            return true;
        }
        return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
    };
    $scope.search = function () {
        $scope.filteredItems = $filter('filter')($scope.tableList, function (item) {
            for (var attr in item) {
                if (searchMatch(item[attr], $scope.query))
                    return true;
            }
            return false;
        });
        // take care of the sorting order
        if ($scope.sort.sortingOrder !== '') {
            $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sort.sortingOrder, $scope.sort.reverse);
        }
        $scope.currentPage = 0;
        // now group by pages
        $scope.groupToPages();
    };
    $scope.groupToPages = function () {
        $scope.pagedItems = [];

        for (var i = 0; i < $scope.filteredItems.length; i++) {
            if (i % $scope.itemsPerPage === 0) {
                $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
            } else {
                $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
            }
        }
    };

    $scope.range = function (size, start, end) {
        var ret = [];
//        console.log(size, start, end);

        if (size < end) {
            end = size;
            start = size - $scope.gap;
        }
        for (var i = start; i < end; i++) {
            if (i >= 0)
                ret.push(i);
        }
//        console.log(ret);
        return ret;
    };

    $scope.prevPage = function () {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };

    $scope.nextPage = function () {
        if ($scope.currentPage < $scope.pagedItems.length - 1) {
            $scope.currentPage++;
        }
    };

    $scope.setPage = function () {
        $scope.currentPage = this.n;
    };
    $scope.controller = {
        isImage: function (item) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    };
}



